import uuid
from typing import Union

import CSYNAC.Log as Log
from CSYNAC.Node import NodeKeeper, Node


class Memery():
    # def __init__(self,self_node:Node):
    def __init__(self, nodename):
        self.dict:dict = {}
        self.nodename = nodename
        self.central_nodename:Union[str,None] = None
        # self.node_info:dict = {self_node.nodename:self_node}
        self.node_keeper:NodeKeeper = NodeKeeper()
        # self.node_info:dict = {}
        # 节点保存处
        self.SynacFolders:dict = {}
        # 此文件夹主要用于存放已设定的同步文件夹
        self.logs:Log.LogKeeper = Log.LogKeeper()
        # 日志管理器
        # -------------------------Node-------------------------------
    def node_self(self) -> Node:
        return self.node_keeper.all_node()[self.nodename]

    def node_add(self,node: Node):
        # if not node.nodename in self.node_info:
        #     self.node_info[node.nodename] = node
        self.node_keeper.add_node(node)

    def node_add_central(self,node:Node):
        self.central_nodename = node.nodename
        self.node_add(node)

    def node_del(self,node_name):
        # del self.node_info[node_name]
        self.node_keeper.pop_node(node_name)

    def node_report(self,name_only=False):
        # return self.node_info
        if name_only:
            return self.node_keeper.all_name_only()
        else:
            return self.node_keeper.all_node()

    # ------------------------------Log--------------------------------
    # 此处位写入一条log的意思
    def log_in(self, message:str, node:Node=None, mtype='normal', eventID=None,):
        if not eventID:
            eventID = uuid.uuid1()
        # self.logs.add_local_log(eventID,message=message, mtype=mtype)
        self.logs.add_log(node,eventID,mtype,message)
    '''
    在我的设想中,有以下几种log
    1. debug:主要用于开发时调试信息,正式使用时不应该出现.
    2. system:系统启动和关闭记录.
    3. group:节点之间协作所需要记录的信息,比如注册,退出等
    4. task_origin :任务框架的信息
    5. task_content:任务内容的信息
    6. cache:提取缓存信息
    7. normal:例外,默认
    '''

    # 提取与一个节点有关的所有信息
    def log_out_by_node(self,nodename):
        return [
            log for log in self.logs.logs
                if log.node==nodename
        ]

    def log_out_by_time(self,start,end):
        return [
            log for log in self.logs.logs
                if log.time >start
                and log.time<end
        ]

    def log_out_by_eventID(self,eventID):
        return [
            log for log in self.logs.logs
            if log.eventID == eventID
        ]


    def log_all(self):
        return self.logs.logs